package com.nomcode.webtextr;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.provider.ContactsContract;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
	
	Thread t;
	ProgressDialog dialog;
	
	private static final int SETTINGS_ID = Menu.FIRST;
	private static final int SENDING_DIALOG = 0;
	
	private String phoneNo;
	private String password; 
	private String serviceProvider;
	private String serverUrl;
	
	private String recipient;
	private String bodyText;
	
	List<ContactPhone> contactPhoneList;
	ContactPhoneAdapter adapter;
	AutoCompleteTextView actv;
	
    /** Called when the activity is first created. */
    @Override	
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        
        contactPhoneList = new ArrayList<ContactPhone>();       
        
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        phoneNo = prefs.getString("phoneNo", null);
        password = prefs.getString("password", null);
        serviceProvider = prefs.getString("serviceProvider", null);
        serverUrl = prefs.getString("serverUrl", "http://cabbagetexter.com");
        
        Button sendButton = (Button) findViewById(R.id.sendButton);
        sendButton.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                showDialog(SENDING_DIALOG);
                t = new Thread() {
                	public void run() {
                		sendMessage();
                	}
                };
                t.start();
            }

        });
        
        if (phoneNo == null || password == null || serviceProvider == null ||
        		phoneNo.equals("") || password.equals("") || serviceProvider.equals(""))
        	launchPreferences();
        
        Thread t2 = new Thread() {
        	public void run() { getContacts(); }
        };
        t2.start();
        
        actv = (AutoCompleteTextView)this.findViewById(R.id.to);
        adapter = new ContactPhoneAdapter(this, contactPhoneList);
        actv.setAdapter(adapter);
        
      
    }
    
    public void getContacts() {
        // get list of ContactPhone
    	// send message to handler with list of ContactPhone
    	Cursor c = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);

    	while(c.moveToNext()) {
    		String contactId = c.getString(c.getColumnIndex(ContactsContract.Contacts._ID));
    		String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
    		String hasPhone = c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
    		if (Integer.parseInt(hasPhone) == 1) {
    			Cursor phoneCursor = getContentResolver().query(
    					ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, 
    					ContactsContract.CommonDataKinds.Phone.CONTACT_ID+"='"+contactId+"'", 
    					null, null);
    			while (phoneCursor.moveToNext()) {
    				String number = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
    				String numberType = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
    				ContactPhone tempCp = new ContactPhone(name, numberType, number);
    				contactPhoneList.add(tempCp);
    			}
    		}
    		
    	}
    	
    	Message msg = new Message();
    	msg.obj = contactPhoneList;
    	handler.sendMessage(msg);

    }
    
    private Handler handler = new Handler() {
    	@Override
    	public void handleMessage(Message msg) {
    		// extract list of ContactPhone
    		// adapter.setContactPhoneList( list of ContactPhone );
    		@SuppressWarnings("unchecked")
			List<ContactPhone> cp = (List<ContactPhone>)msg.obj;
    		adapter.setContactPhoneList(cp);
    		actv.setAdapter(adapter);
    	}
    };
    
    public void sendMessage() {
    	try {
	    	EditText edTxRecipient = (EditText) findViewById(R.id.to);
	    	EditText edTxBodyText = (EditText) findViewById(R.id.bodyText); 
	    	recipient = edTxRecipient.getText().toString();
	    	bodyText = edTxBodyText.getText().toString();
	    	String encBodyText = null;
			encBodyText = java.net.URLEncoder.encode(bodyText,"UTF-8");
			DefaultHttpClient client = new DefaultHttpClient();
	    	String sendString = serverUrl + "/send.php?u=" + phoneNo + "&p=" + password + "&s=" + serviceProvider + "&d=" + recipient + "&m=" + encBodyText;
	    	HttpPost httpPost = new HttpPost(sendString);
	    	HttpResponse response = client.execute(httpPost);
	    	InputStream in = response.getEntity().getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            String responseCode = reader.readLine();
            in.close();
	    	removeDialog(SENDING_DIALOG);
	    	handleServerResponse(responseCode);
    	} catch (Exception e) {
    		removeDialog(SENDING_DIALOG);
    		handleServerResponse("-3");
    	}
    }
    
    public void handleServerResponse(final String rspCode) {
    	
    	boolean success = false;
    	final CharSequence TOAST_RSP_TEXT;
    	int rspCodeInt;
    	try {
    		rspCodeInt = Integer.parseInt(rspCode);
    	} catch (NumberFormatException e) {
    		rspCodeInt = -4;
    	}
    	
    	
    	if (rspCodeInt == -1)
    		TOAST_RSP_TEXT = "Error! Invalid login details.";
    	else if (rspCodeInt == -2)
    		TOAST_RSP_TEXT = "Error! Unable to connect to service provider's website.";
    	else if (rspCodeInt == -5)
    		TOAST_RSP_TEXT = "Error! Unexpected response from service provider website.";
    	else if (rspCodeInt == -3)
    		TOAST_RSP_TEXT = "Fatal Error! Unable to contact server at all.";
    	else if (rspCodeInt == -4)
    		TOAST_RSP_TEXT = "Error! Invalid response.";
    	else if (rspCodeInt >= 0) {
    		TOAST_RSP_TEXT = "Message sent successfully. You have " + rspCodeInt + " web texts remaining.";
    		success = true;
    	}
    	else
    		TOAST_RSP_TEXT = "Impossible Error. It's Guru Meditation time!";

    	this.runOnUiThread(new Runnable() {
    	    public void run() {
    	    	Toast toast = Toast.makeText(getApplicationContext(), TOAST_RSP_TEXT, Toast.LENGTH_LONG);
    	    	toast.show();
    	    }
    	});
    	if (success) insertMessageIntoDb();
    }
    
    public void insertMessageIntoDb() {
    	ContentValues values = new ContentValues();
    	values.put("address", recipient);
    	values.put("body", bodyText);
    	getContentResolver().insert(Uri.parse("content://sms/sent"), values);
    }
    
    @Override
    protected Dialog onCreateDialog(int id) {
    	switch(id) {
    	case SENDING_DIALOG: {
    		dialog = new ProgressDialog(this);
    		dialog.setMessage("Sending message...");
    		dialog.setIndeterminate(true);
    		dialog.setCancelable(true);
    		return dialog;
    	}
    	}
    	return null;
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        menu.add(0, SETTINGS_ID, 0, R.string.menuPrefs);
        return true;
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        switch(item.getItemId()) {
            case SETTINGS_ID:
                launchPreferences();
                return true;
        }

        return super.onMenuItemSelected(featureId, item);
    }
    
    private void launchPreferences() {
    	Intent i = new Intent(this, Preferences.class);
    	startActivity(i);
    }
}